import Cookies from 'js-cookie'

import {setToken, removeToken} from '@/util/auth'
import {setStore, getStore} from '@/util/store'
import {login, logout} from '@/api/login'
import {getMenu} from '@/api/system/menu'
import {encrypt} from '@/util/crypto'
import {isURL, validatenull} from '@/util/validate'
import {deepClone} from '@/util/util'
import webiste from '@/config/website'
import {sm3Encrypt} from '@/util/smcrypto'

function addPath(ele, first) {
  const menu = webiste.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    name: propsConfig.name || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  if (!isChild) ele[propsDefault.children] = [];
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach(child => {
      addPath(child);
    })
  }
}

const user = {
  state: {
    userInfo: getStore({name: 'userInfo'}) || [],
    permission: getStore({name: 'permission'}) || {},
    roles: [],
    menu: getStore({name: 'menu'}) || [],
    menuAll: [],
    token: getStore({name: 'token'}) || '',
  },
  actions: {
    //根据用户名登录
    login({commit, state, getters}, userInfo) {
      const cipher = encrypt(userInfo.pwd, getters.secretKey);
      // const sm3 = require('@/util/sm-crypto/sm3');
      let sm3pass = sm3Encrypt(userInfo.pwd);
      userInfo.password = sm3pass;
      return new Promise((resolve, reject) => {
        login(userInfo).then(data => {
          if (data.success) {
            commit('SET_TOKEN', data.data.accessToken);
            commit('SET_USERIFNO', data.data);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
            if (userInfo.rememberPwd) {
              Cookies.set('ecgap_name', userInfo.account, {expires: getters.cookieExpire});
              Cookies.set('ecgap_cipher', cipher, {expires: getters.cookieExpire});
            } else {
              Cookies.remove('ecgap_name');
              Cookies.remove('ecgap_cipher');
            }
            resolve(data.data);
          } else {
            reject(data);
          }
        }).catch(error => {
          reject(error);
        })
      })
    },
    //获取应用菜单
    getMenu({commit}) {
      return new Promise((resolve, reject) => {
        getMenu().then((res) => {
          const data = res.data
          let menu = deepClone(data);
          menu.forEach(ele => {
            addPath(ele, true);
          })
          commit('SET_MENU', menu)
          // dispatch('GetButtons');
          resolve(menu)
        }).catch(error => {
          reject(error);
        })
      })
    },
    //登出
    logout({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_MENU', [])
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token)
      state.token = token;
      setStore({name: 'token', content: state.token, type: 'session'})
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({name: 'userInfo', content: state.userInfo})
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({name: 'menu', content: state.menu, type: 'session'})
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      let result = [];

      function getCode(list) {
        list.forEach(ele => {
          if (typeof (ele) === 'object') {
            const chiildren = ele.children;
            const code = ele.code;
            if (chiildren) {
              getCode(chiildren)
            } else {
              result.push(code);
            }
          }

        })
      }

      getCode(permission);
      state.permission = {};
      result.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({name: 'permission', content: state.permission, type: 'session'})
    }
  }

}
export default user
